package com.lagou.edu.controller;

import cn.hutool.core.util.RandomUtil;
import com.lagou.edu.feign.SendCodeFeign;
import com.lagou.edu.pojo.LagouAutoCode;
import com.lagou.edu.service.ICodeService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private ICodeService codeService;

    @Autowired
    private SendCodeFeign sendCodeFeign;

    @PostMapping("/create")
    public boolean createCode(String email){
        String code = RandomUtil.randomString("0123456789", 6);
        LagouAutoCode lagouAutoCode = new LagouAutoCode();
        lagouAutoCode.setCode(code);
        lagouAutoCode.setEmail(email);
        lagouAutoCode.setCreatetime(new Date());
        lagouAutoCode.setExpiretime(new Date(new Date().getTime() + 600000));
        //保存验证码到数据库
        LagouAutoCode result = codeService.saveCode(lagouAutoCode);
        if(result != null){
            boolean isSended = sendCodeFeign.sendCode(email, code);
            if(isSended){
                return true;
            }else{
                return false;
            }
        }else {
            return false;
        }
    }

    @PostMapping("/validate")
    public Integer validate(String email,String code){
        Integer result = codeService.validateCodeByEmail(email, code);
        return result;
    }
}
